package com.starsky.common.utils.easypoi;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.annotation.ExcelEntity;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.starsky.common.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * Excel工具类
 */
public class ExcelUtils {

	/**
	 * 导入Excel转换为List<T>
	 *
	 * @param filePath		文件名
	 * @param titleRows		标头行
	 * @param headerRows	标头行
	 * @param clazz			对象Class
	 */
	public  <T> List<T> importExcel(String filePath, int titleRows, int headerRows, Class<T> clazz){
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), clazz, params);
        }catch (Exception e) {
            e.printStackTrace();

        }
        return list;
    }

	/**
	 * 导入Excel转换为List<T>
	 *
	 * @param file			http上传的文件
	 * @param titleRows		标头行
	 * @param headerRows	标头行
	 * @param clazz			对象Class
	 */
	public static <T> List<T> importExcel(MultipartFile file, int titleRows, int headerRows, Class<T> clazz){
		if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
	}

	/**
	 * Excel导出
	 *
	 * @param response  response
	 * @param fileName  文件名
	 * @param list      数据List
	 * @param pojoClass 对象Class
	 */
	public static void exportExcel(HttpServletResponse response, String fileName, Collection<?> list,
                                   Class<?> pojoClass) throws IOException {
		if (StringUtils.isBlank(fileName)) {
			// 当前日期
			fileName = DateUtils.format(new Date(),null);
		}

		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojoClass, list);
		Sheet sheet1 = workbook.getSheetAt(0);
		sheet1.setDefaultColumnWidth(50 * 256);
		sheet1.setDefaultRowHeight((short) (2 * 256));
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-Type", "application/vnd.ms-excel");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
		ServletOutputStream out = response.getOutputStream();
		workbook.write(out);
		out.flush();
		out.close();
	}

	/**
	 * Excel导出，先sourceList转换成List<targetClass>，再导出
	 *
	 * @param response    response
	 * @param fileName    文件名
	 * @param sourceList  原数据List
	 * @param targetClass 目标对象Class
	 */
	public static void exportExcelToTarget(HttpServletResponse response, String fileName, Collection<?> sourceList,
                                           Class<?> targetClass) throws Exception {
		List<Object> targetList = new ArrayList<>(sourceList.size());
		for (Object source : sourceList) {
			Object target = targetClass.newInstance();
			BeanUtils.copyProperties(source, target);
			targetList.add(target);
		}

		exportExcel(response, fileName, targetList, targetClass);
	}

	public static void main(String[] args) {
//读取文件
//		List<UplinkDataImport2DTO> dtos = ExcelUtils.importExcel(file, titleRows, headRows, UplinkDataImport2DTO.class);
//        List<UplinkDataImport2DTO> dtos = ExcelImportUtil.importExcel(inputStream, UplinkDataImport2DTO.class, params);

//导出
//        List<ExcelTestEntity> list = new ArrayList<>();
//        ExcelTestEntity excelTest = new ExcelTestEntity();
//        excelTest.setId(10000);
//        excelTest.setFileName("测试excel.xlsx");
//        excelTest.setFilePath("c:\\excel");
//        excelTest.setType(1);
//        list.add(excelTest);
//        ExcelUtils.exportExcelToTarget(response, null, list, ExcelTestEntity.class);
	}
}
